package com.ocom.exposeapi.util;

import com.ocom.common.utils.abc.HttpClientUtils;
import com.ocom.common.utils.abc.RSAUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;

/**
 * 中国农业银行缴费中心
 * 直连商户平台
 * 验签和加签工具类
 */
@Component
public class SignatureAndVerification {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 读取RSA并验证公钥签名
     */
    public boolean read_RSA_and_verify_sign(String publicKeyString, String requsetBody, String signature) {
        boolean flag = false;

        try {
            PublicKey publicKey = RSAUtil.getPublicKey(publicKeyString);
            System.out.println("-----------------公钥--------------------");
            System.out.println(publicKeyString);
            System.out.println("-----------------公钥--------------------");
            Signature verifySign = Signature.getInstance("SHA1withRSA");
            verifySign.initVerify(publicKey);
            // 用于验签的数据
            verifySign.update(requsetBody.getBytes("utf-8"));
            flag = verifySign.verify(com.alibaba.fastjson.util.Base64.decodeFast(signature));// 验签由第三方做
            System.out.println("verifySign is " + flag);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            return flag;
        }

    }

    /**
     * 加签名
     *
     * @param dataString
     * @return
     */
    public String signWhithsha1withrsa2(String privateKeyString, String dataString) {
        String signatureString = null;
        try {
//            logger.info("-----------------开始签名--------------------");
            PrivateKey privateKey = RSAUtil.getPrivateKey(privateKeyString);

            // SHA1withRSA算法进行签名
            Signature sign = Signature.getInstance("SHA1withRSA");
            sign.initSign(privateKey);
            byte[] data = dataString.getBytes("utf-8");
            byte[] dataBase = Base64.encodeBase64(data);
            // 更新用于签名的数据
            sign.update(dataBase);
            byte[] signature = sign.sign();
            signatureString = new String(Base64.encodeBase64(signature));
        } catch (Exception e) {
            logger.info("-----------------签名失败--------------------：{}", e.getMessage());
            e.printStackTrace();
        }
        return signatureString;
    }

    /**
     * 接收报文返回requsetBody和使用base64解析后的requsetBody以及缴费中心传送的签名
     */

    public Map<String, String> requestBodyOfBase64(HttpServletRequest request) {
        Map<String, String> requestMap = new HashMap<String, String>();
        // 接收报文
        String requestContent = null;
        try {
            requestContent = HttpClientUtils.getRequestBody(request)
                    .trim();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (logger.isWarnEnabled()) {
            logger.info("收到的报文：{}", requestContent);
        }
        String signatureString = requestContent.substring(0,
                requestContent.indexOf("||"));
        logger.info("截取报文的signatureString:", signatureString);
        String requsetBody = requestContent.substring(signatureString
                .length() + 2);
        logger.info("截取报文的requsetBody:", requsetBody);
        String requsetBodyOfDecoded = new String(
                com.alibaba.fastjson.util.Base64.decodeFast(requsetBody));
        System.out.println("-----解析完成后的requsetBody-------" + requsetBodyOfDecoded);
        //使用base64解析完成后的requsetBody
        requestMap.put("requsetBodyOfDecoded", requsetBodyOfDecoded);
        //解析前的requsetBody
        requestMap.put("requsetBody", requsetBody);
        //获取缴费中心传送过来的签名
        requestMap.put("signatureString", signatureString);
        return requestMap;

    }


}
